<!--vue模板-->
<template>
  <div style="background-color: #fff">
    <!--咨询信息-->
    <div class="tip">咨询信息</div>
    <el-row>
      <el-col
        :span="4"
        style="
          height: 40px;
          padding-right: 10px;
          line-height: 40px;
          text-align: right;
        "
        >联系工程师:</el-col
      >
      <el-col :span="20"
        ><el-select
          v-model="data.saler"
          placeholder="请选择"
          style="width: 300px"
        >
          <el-option
            v-for="item in saleoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>
    </el-row>

    <el-row>
      <el-col
        :span="4"
        style="
          height: 40px;
          padding-right: 10px;
          line-height: 40px;
          text-align: right;
        "
        >询价类型:</el-col
      >
      <el-col :span="20">
        <el-radio-group v-model="data.type">
          <el-radio :value="1" size="large">询价单</el-radio>
          <el-radio :value="2" size="large">咨询单</el-radio>
        </el-radio-group>
      </el-col>
    </el-row>

    <div class="tip">产品信息</div>
    <el-table :data="data.product" style="width: 100%">
      <el-table-column label="产品图片" width="180">
        <template #default="{ row }">
          <img
            :src="row.picurl"
            alt="产品图片"
            style="max-width: 100%; height: auto"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="产品名称" />
      <el-table-column prop="spec" label="产品型号" width="180" />
      <el-table-column prop="price" label="产品价格" width="180" />
      <el-table-column prop="num" label="需求数量" width="180">
        <template #default="{ row }">
          <el-input-number
            v-if="row.num !== '' && row.num !== 0"
            v-model="row.num"
            :min="1"
          />
          <el-input-number v-else v-model="row.num" :min="1" :value="1" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" />
    </el-table>
    <el-button type="primary" @click="add">添加产品</el-button>

    <el-button type="primary" @click="save">保存</el-button>

    <!--选择产品-->
    <ChooseProduct
      ref="chooseProductRef"
      :visible="isShowChooseProduct"
      @close="isShowChooseProduct = false"
      @choose="chooseProduct"
    />
  </div>
</template>

<!--vue 组件选项定义-->
<script setup>
import { ref } from "vue";
import ChooseProduct from "@/views/product/ChooseProduct.vue";
import { ElMessage } from "element-plus";
import { getUser } from "@/utils/session.js";
import { saveEnquiry } from "@/api/enquiry.js";
import { useRouter } from "vue-router";
import { getById } from "@/api/product.js";
const router = useRouter();
//接收产品详情页传过来的参数
async function proDuctId() {
  let id = router.currentRoute.value.query.id;
  if (id) {
    //如果不是空才会传到服务器查询产品信息
    let ref = await getById({ id });
    ref.data.num = 1;
    data.value.product.push(ref.data);
  }
}
// 询价单号递增变量
let enquiryIndex = 0;
// 生成询价单号
function generateEnquiryNo() {
  const user = getUser();

  // 获取当前日期并格式化
  const date = new Date();
  const yyyy = date.getFullYear();
  const mm = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始
  const dd = String(date.getDate()).padStart(2, "0");

  // 生成询价单号
  enquiryIndex++; // 自增
  return `${yyyy}${mm}${dd}${user.id}${enquiryIndex}`; // 组合为询价单号
}

//是否显示选择产品
const isShowChooseProduct = ref(false);
const chooseProductRef = ref(null);
//工程师选项
const saleoptions = ref([]);
const data = ref({
  saler: "",
  type: 1,
  product: []
});

//添加产品
function add() {
  isShowChooseProduct.value = true;
  chooseProductRef.value.clear();
}

//--选择产品--
function chooseProduct(rows) {
  console.log("rows>>>", rows);
  //遍历选择的产品 追加上去
  rows.forEach(el => {
    //遍历data.value.product  查看要添加的产品是否存在
    let flag = false; //默认不存在
    for (let i = 0, len = data.value.product.length; i < len; i++) {
      let p = data.value.product[i];
      if (el.id == p.id) {
        flag = true;
        break;
      }
    }
    if (!flag) {
      let tmp = {};
      tmp.num = 1;
      tmp.picurl = el.picurl;
      tmp.pid = el.id;
      tmp.price = el.price;
      tmp.name = el.name;
      tmp.spec = el.spec;
      data.value.product.push(tmp);
    }
  });
}

function save() {
  if (data.value.product.length == 0) {
    ElMessage.warning("请选择产品");
    return;
  }

  // 从登录信息中获取
  let user = getUser();
  data.value.createUserId = user.id;
  data.value.customerName = user.account;

  // 生成询价单号并赋值
  data.value.code = generateEnquiryNo();

  // 构建 enquiryDetails
  let enquiryDetails = data.value.product.map(product => ({
    pid: product.pid,
    num: product.num,
    picurl: product.picurl,
    productName: product.productName,
    spec: product.spec,
    price: product.price
    // 你可以根据需要添加更多字段
  }));

  // 将 enquiryDetails 添加到 data.value 中
  const payload = {
    ...data.value,
    enquiryDetails: enquiryDetails
  };

  // 调用saveEnquiry接口
  saveEnquiry(payload)
    .then(response => {
      ElMessage.success("保存成功");
      // 清空表单
      resetForm();
    })
    .catch(error => {
      ElMessage.error("保存失败: " + error.message);
    });

  console.log(">>>", payload);
}

function resetForm() {
  data.value = {
    saler: "",
    type: 1,
    product: []
  };
}
proDuctId();
//表格数据
</script>

<!--vue样式 scoped当前样式只适用于当前组件-->
<style scoped>
.tip {
  height: 40px;
  line-height: 40px;
  background-color: #eee;
  border: solid 1px #ddd;
}
</style>
